#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os


def read_file(filename):
    if os.path.exists(filename):
        with open(filename) as f:
            return f.read().strip(' \n')
    else:
        return '0'


def to_bytes(s):
    s = s.strip('Bb \n')
    unit = s[-1]
    if unit in ('K', 'k'):
        return int(float(s[:-1]) * (2 ** 10))
    elif unit in ('M', 'm'):
        return int(float(s[:-1]) * (2 ** 20))
    elif unit in ('G', 'g'):
        return int(float(s[:-1]) * (2 ** 30))
    elif unit in ('T', 't'):
        return int(float(s[:-1]) * (2 ** 40))
    else:
        return int(float(s))


class Bcache(object):
    def __init__(self):
        pass

    @staticmethod
    def dirty_data(dev):
        s = read_file('/sys/block/%s/bcache/dirty_data' % dev)
        return to_bytes(s)

    @staticmethod
    def disk_stat(total, dirty_data):
        total = to_bytes(total) / 1024 / 1024
        dirty_data = dirty_data / 1024 / 1024
        return {
            'disk': '0',
            'online': '1',
            'total': str(total),
            'used': str(dirty_data),
            'cache': '0',
            'cached': '0',
            'wbcount': '0',
            'wbtotal': '0',
            'wbused': '0',
        }


class BcacheSuperShow(object):
    """
    [match1.rack1.node152 cb]bcache-super-show /dev/sdaa

    sb.magic		ok
    sb.first_sector		8 [match]
    sb.csum			9BE6E630D2FF9A3F [match]
    sb.version		1 [backing device]

    dev.label		(empty)
    dev.uuid		908516b6-c9db-4b67-b608-3f2cf41ded41
    dev.sectors_per_block	1
    dev.sectors_per_bucket	1024
    dev.data.first_sector	16
    dev.data.cache_mode	1 [writeback]
    dev.data.cache_state	2 [dirty]

    cset.uuid		313d414b-b02f-47c5-843b-04bed453154e
    """
    def __init__(self, dev):
        self.dev = dev


if __name__ == '__main__':
    total = '893.8GB'
    dirty_data = Bcache.dirty_data('sdf')
    print dirty_data
    print Bcache.disk_stat(total, dirty_data)
